<?php
namespace App\Http\Controllers;

use App\Exceptions\ValidateException;
use Illuminate\Http\JsonResponse;
use Laravel\Lumen\Routing\Controller as BaseController;
use Auth;

class Controller extends BaseController
{
    /**
     * Return JSON Data
     *
     * @param int    $code
     * @param string $message
     * @param        $data
     * @return JsonResponse
     */
    protected function result($code = 200, $message = '', $data = [])
    {
        $token = Auth::user();
        if (!is_object($data)) {
            $token = isset($data['token']) ? $data['token'] : Auth::user();
            if (isset($data['token'])) unset($data['token']);
        }

        return new JsonResponse(['code' => $code, 'message' => $message, 'data' => $data, 'token' => $token]);
    }

    /**
     * Return Array
     *
     * @param array  $data
     * @param string $message
     * @return JsonResponse
     */
    protected function success($data = [], $message = '')
    {
        if(is_array($data) && empty($data)) {
            $data = (object)[];
        }

        return $this->result(200, $message, $data);
    }

    /**
     * Return Array
     *
     * @param     $message
     * @param int $code
     * @return JsonResponse
     */
    protected function fail($message, $code = -200)
    {
        return $this->result($code, $message);
    }

    /**
     * Return Array
     *
     * @param ValidateException $e
     * @return JsonResponse
     */
    protected function validateError(ValidateException $e)
    {
        return $this->result(-200, $e->getMessage(), (object)[]);
    }

    /**
     * 搜索 查询 Map [field 字段, value 关键字, operation 操作符]
     *
     * @param array $map
     * @return array
     */
    protected function searchMap($map = ['field', 'value', 'operation'])
    {
        $result = [];
        foreach ($map as $val) {
            $field = $val[0];
            $value = !is_array($val[1]) ? (!empty(trim($val[1])) ? trim($val[1]) : null) : $val[1];
            $operation = $val[2];

            if ($field === 'created_at') {
                $value = $value === null ? null : strtotime($value);
            }

            if ($operation === 'like') {
                $value = $value === null ? null : '%'.$value.'%';
            }

            $result[] = ['field' => $field, 'value' => $value, 'operation' => $operation];
        }

        return $result;
    }
}
